package cn.juque.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.fastjson.FastJsonReader;
import cn.juque.common.fastjson.FastJsonWriter;
import cn.juque.common.fastjson.IFastJsonFilter;
import cn.juque.common.fastjson.abstracts.AbstractTypeReference;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.util.List;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>fastjson工具类</li>
 * @date 2022/7/13 17:44
 **/
public class FastJsonUtil {

    private FastJsonUtil() {
    }

    /**
     * 对象转json字符串
     *
     * @param object  对象
     * @param feature JSONWriter
     * @return String
     */
    public static String toJsonString(Object object, FastJsonWriter.Feature... feature) {
        return JSON.toJSONString(object, feature);
    }

    /**
     * 对象转json字符串
     *
     * @param object  对象
     * @param filter 过滤器
     * @param feature JSONWriter
     * @return String
     */
    public static String toJsonString(Object object, IFastJsonFilter filter, FastJsonWriter.Feature... feature) {
        return JSON.toJSONString(object, filter, feature);
    }

    /**
     * 字符串转对象
     *
     * @param json          字符串
     * @param typeReference 对象的泛型
     * @param features      JSONReader
     * @param <T>           泛型
     * @return 对象
     */
    public static <T> T parseObject(String json, AbstractTypeReference<T> typeReference,
        FastJsonReader.Feature... features) {
        return JSON.parseObject(json, typeReference, features);
    }

    /**
     * 字符串转JSON对象
     *
     * @param json 字符串
     * @return JSONObject
     */
    public static JSONObject parseObject(String json) {
        return JSON.parseObject(json);
    }

    /**
     * 字符串转列表
     *
     * @param json     字符串
     * @param tClass   目标类
     * @param features JSONReader
     * @param <T>      泛型
     * @return list
     */
    public static <T> List<T> parseArray(String json, Class<T> tClass, FastJsonReader.Feature... features) {
        if (CharSequenceUtil.isEmpty(json)) {
            return CollUtil.newArrayList();
        }
        return JSON.parseArray(json, tClass, features);
    }
}
